<?php
/**
 * ActiveOffer.class.php
 *
 * @author camfee <camfee@foxmail.com>
 * @date   18-1-2 下午9:17
 */

namespace Center;

use Common\ModuleBase;
use Common\Bridge;

class ActiveOffer extends ModuleBase
{
    protected static $_conf = [
        'db' => [
            'w' => Bridge::DB_CENTER_W,
            'r' => Bridge::DB_CENTER_R
        ],
        'table' => 'ActiveOffer',
        'fields' => [
            'Id' => self::VAR_TYPE_KEY,
            'ActiveId' => self::VAR_TYPE_INT,
            'UserId' => self::VAR_TYPE_INT,
            'OfferPrice' => self::VAR_TYPE_STRING,
            'Status' => self::VAR_TYPE_INT,
            'UpdateTime' => self::VAR_TYPE_STRING,
            'CreateTime' => self::VAR_TYPE_STRING,
        ],
        'mc' => Bridge::MEMCACHE_DEFAULT,
        // 可选, MC KEY, "KeyName:%d", %d会用主键ID替代
        'mckey' => 'ActiveOffer:%d',
        // 可选, 超时时间, 默认不过期
        'mctime' => 86400,
    ];

    const STATUS_WIN = 1;

    const MC_WIN_LIST = 'Active_Win_List:{ActiveId}';
    const MC_MY_LIST = 'Active_My_List:{ActiveId}:{UserId}';
    const MC_MY_ACTIVE_LIST = 'Active_My_Active_List:{UserId}';
    const MC_ALL_LIST = 'Active_All_List:{ActiveId}';
    const MC_ACTIVE_USER_LIST = 'Active_User_List:{ActiveId}';
    const MC_MY_GIFT_LIST = 'Active_My_Gift_List:{UserId}';
    const UPDATE_DEL_CACHE_LIST = true; // 更新是否清除列表缓存
    // 列表缓存
    protected static $_cache_list_keys = [
        self::MC_WIN_LIST => [
            self::CACHE_LIST_TYPE => self::CACHE_LIST_TYPE_MC,
            self::CACHE_LIST_FIELDS => 'ActiveId',
        ],
        self::MC_MY_ACTIVE_LIST => [
            self::CACHE_LIST_TYPE => self::CACHE_LIST_TYPE_MC,
            self::CACHE_LIST_FIELDS => 'UserId',
        ],
        self::MC_MY_LIST => [
            self::CACHE_LIST_TYPE => self::CACHE_LIST_TYPE_MC,
            self::CACHE_LIST_FIELDS => ['ActiveId', 'UserId'],
        ],
        self::MC_ALL_LIST => [
            self::CACHE_LIST_TYPE => self::CACHE_LIST_TYPE_MC,
            self::CACHE_LIST_FIELDS => 'ActiveId',
        ],
        self::MC_ACTIVE_USER_LIST => [
            self::CACHE_LIST_TYPE => self::CACHE_LIST_TYPE_MC,
            self::CACHE_LIST_FIELDS => 'ActiveId',
        ],
        self::MC_MY_GIFT_LIST => [
            self::CACHE_LIST_TYPE => self::CACHE_LIST_TYPE_MC,
            self::CACHE_LIST_FIELDS => 'UserId',
        ],
    ];

    /**
     * 获取我的活动奖品列表
     *
     * @param     $uid
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public static function getMyActive($uid, $offset = -1, $limit = 20)
    {
        $where = [
            'UserId' => $uid,
        ];
        $extra = [
            'type' => parent::MOD_TYPE_MEMCACHE,
            'mckey' => self::MC_MY_ACTIVE_LIST,
            'mtime' => 86400,
            'fields' => 'ActiveId',
            'listkey' => 'ActiveId',
            'listval' => 'ActiveId'
        ];

        $list = parent::getDataByFields($where, $extra);
        if (!empty($list['data']) && $offset != -1) {
            $list['data'] = array_slice($list['data'], $offset, $limit);
        }

        return $list;
    }

    /**
     * 获取我的活动奖品列表
     *
     * @param     $uid
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public static function getMyGift($uid, $offset = 0, $limit = 20)
    {
        $where = [
            'UserId' => $uid,
            'Status' => 1
        ];
        $extra = [
            'type' => parent::MOD_TYPE_MEMCACHE,
            'mckey' => self::MC_MY_GIFT_LIST,
            'mtime' => 86400,
            'fields' => 'ActiveId',
            'listkey' => 'ActiveId',
            'listval' => 'ActiveId'
        ];

        $list = parent::getDataByFields($where, $extra);
        if (!empty($list['data'])) {
            $list['data'] = array_slice($list['data'], $offset, $limit);
        }

        return $list;
    }

    /**
     * 获取获奖列表
     *
     * @param $activeid
     * @return array
     */
    public static function getWinList($activeid)
    {
        $where = [
            'ActiveId' => $activeid,
            'Status' => 1
        ];
        $extra = [
            'type' => parent::MOD_TYPE_MEMCACHE,
            'mckey' => self::MC_WIN_LIST,
            'mtime' => 86400,
            'fields' => '*',
            'listkey' => 'Id',
        ];

        return parent::getDataByFields($where, $extra);
    }

    /**
     * 获取用户出价
     *
     * @param $activeid
     * @param $uid
     * @return array|bool
     */
    public static function getMyList($activeid, $uid)
    {
        if (empty($activeid) || empty($uid)) {
            return false;
        }
        $where = [
            'ActiveId' => $activeid,
            'UserId' => $uid
        ];
        $extra = [
            'type' => parent::MOD_TYPE_MEMCACHE,
            'mckey' => self::MC_MY_LIST,
            'mtime' => 86400,
            'fields' => '*',
            'listkey' => 'Id',
        ];

        return parent::getDataByFields($where, $extra);
    }

    /**
     * 获取活动我的所有出价
     *
     * @param array $activeid
     * @param int   $uid
     * @return array|bool
     */
    public static function getMyActivesOffers($activeid, $uid)
    {
        if (empty($activeid) || empty($uid)) {
            return false;
        }
        $my_all_offer_list = ActiveOffer::getInfoByActiveIds($activeid, $uid);
        $my_all_offers = $my_all_offer = $win_price = [];
        if (!empty($my_all_offer_list['data'])) {
            foreach ($my_all_offer_list['data'] as $ov) {
                $my_all_offers[$ov['ActiveId']][$ov['CreateTime']][] = $ov;
            }
            unset($my_all_offer_list);
            $single = $double = [];
            foreach ($my_all_offers as $aid => $ov) {
                krsort($ov);
                $i = 0;
                foreach ($ov as $pv) {
                    if (count($pv) == 1) {
                        if ($pv[0]['Status'] == ActiveOffer::STATUS_WIN) {
                            $win_price[$aid] = $pv[0]['OfferPrice'];
                        }
                        $single[$pv[0]['OfferPrice']] = $i;
                        $my_all_offer[$aid][$i] = [
                            'Price' => '￥' . $pv[0]['OfferPrice'],
                            'Time' => $pv[0]['CreateTime'],
                            'Status' => $pv[0]['Status']
                        ];
                    } else {
                        foreach ($pv as $tk => $tv) {
                            if ($tk == 0) {
                                $my_all_offer[$aid][$i] = [
                                    'MaxPrice' => $tv['OfferPrice'],
                                    'Time' => $tv['CreateTime'],
                                    'Status' => $tv['Status']
                                ];
                                $double[$i]['MaxPrice'] = $tv['OfferPrice'];
                            }
                            if ($tv['Status'] == ActiveOffer::STATUS_WIN) {
                                $my_all_offer[$aid][$i]['Status'] = $tv['Status'];
                                $win_price[$aid] = $tv['OfferPrice'];
                            }
                            if ($tk == (count($pv) - 1)) {
                                $my_all_offer[$aid][$i]['MinPrice'] = $tv['OfferPrice'];
                                $my_all_offer[$aid][$i]['Price'] = '￥' . $tv['OfferPrice'] . '~' . $my_all_offer[$aid][$i]['MaxPrice'];
                                $double[$i]['MinPrice'] = $tv['OfferPrice'];
                            }
                        }
                    }
                    $i++;
                }
            }
            unset($my_all_offers);
            if (!empty($double) && !empty($single)) {
                foreach ($double as $dv) {
                    foreach ($single as $sk => $sv) {
                        if ($sk >= $dv['MinPrice'] && $sk <= $dv['MinPrice']) {
                            unset($my_all_offer[$sv]);
                        }
                    }
                }
            }
        }

        return ['offers' => $my_all_offer, 'wins' => $win_price];
    }

    /**
     * 根据活动ids获取用户所有出价
     *
     * @param array $activeid
     * @param int   $uid
     * @return array
     */
    public static function getInfoByActiveIds($activeid, $uid)
    {
        $where = [
            'ActiveId IN' => $activeid,
            'UserId' => $uid
        ];
        $extra = [
            'type' => parent::MOD_TYPE_DB,
            'fields' => 'Id,ActiveId,OfferPrice,Status,CreateTime',
            'listkey' => 'Id',
        ];

        return parent::getDataByFields($where, $extra);
    }

    /**
     * 获取所有出价
     *
     * @param $activeid
     * @return array
     */
    public static function getAllList($activeid, $limit = 9999, $mc = false)
    {
        $key = str_replace('{ActiveId}', $activeid, self::MC_ALL_LIST);
        $data = self::getMC()->get($key);
        if (empty($data) || $mc) {
            $sql = 'SELECT OfferPrice,COUNT(UserId) as Num FROM ActiveOffer WHERE ActiveId=' . $activeid . ' GROUP BY OfferPrice ORDER BY Num ASC  LIMIT ' . $limit;
            $data = self::getPdo()->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
            if (!empty($data)) {
                self::getMC()->set($key, $data, self::$_conf['mctime']);
            }
        }

        return !empty($data) ? $data : [];
    }


    /**
     * 获取所有出价
     *
     * @param $activeid
     * @return array
     */
    public static function getListByActId($activeid, $limit = 999, $mc = false)
    {
        $key = str_replace('{ActiveId}', $activeid, self::MC_ACTIVE_USER_LIST);
        $data = self::getMC()->get($key);
        if (empty($data) || $mc) {
            $sql = 'SELECT OfferPrice, UserId, Status, CreateTime FROM ActiveOffer WHERE ActiveId=' . $activeid . ' ORDER BY OfferPrice ASC LIMIT ' . $limit;
            $data = self::getPdo()->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
            if (!empty($data)) {
                self::getMC()->set($key, $data, self::$_conf['mctime']);
            }
        }

        return !empty($data) ? $data : [];
    }
    /**
     * 批量添加出价
     *
     * @param $data
     * @return array
     */
    public static function adds($data)
    {
        $res = [];
        if (empty($data['ActiveId']) && count($data) > 0) {
            foreach ($data as $v) {
                $res[] = self::add($v, 'ignore');
            }
        }

        return !empty($res) ? $res[0] : [];
    }

    /**
     * @see ModuleBase::add() 新增
     * @see ModuleBase::update() 更新
     * @see ModuleBase::getInfoByIds() 按id查询
     * @see ModuleBase::getList() 条件查询
     * @see ModuleBase::delete() 删除
     */

}